<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>对虾管理</el-breadcrumb-item>
      <el-breadcrumb-item>农资管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row
      class="globalHeader"
      style="
        margin-bottom: 20px;
        padding-bottom: 45px;
        background-color: #eaedf1;
      "
    >
      <el-col :span="4">
        <i class="el-icon-grape"></i>
        <span>农资管理</span>
      </el-col>
    </el-row>
    <!-- 卡片视图区域 -->
    <el-tabs type="border-card">
      <!-- 入库记录 -->
      <el-tab-pane label="入库记录">
        <!-- 列表区域 -->
        <el-row>
          <el-col style="width: 100px; float: right; margin-left: 10px">
            <el-button
              type="primary"
              @click="addDialogVisible = true"
              :disabled="!permissionVisable.traceability_agricultural_add"
              >农资入库</el-button
            >
          </el-col>
          <el-col style="width: 100px; float: right">
            <el-select v-model="selectType1" @change="typeChange1">
              <el-option
                v-for="item in type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-table :data="SuppliesInList" border stripe>
          <!-- :data: 放入数据源 -->
          <!-- border： 加入边框线 -->
          <!-- type="index"： 索引列 -->
          >
          <el-table-column type="index"> </el-table-column>
          <el-table-column
            prop="suppliesName"
            label="农资名称"
          ></el-table-column>
          <el-table-column
            prop="inTime"
            label="入库日期"
            width="180px"
          ></el-table-column>
          <el-table-column prop="inOperator" label="操作人"></el-table-column>
          <el-table-column prop="warehouse" label="仓库号"></el-table-column>
          <el-table-column
            prop="inNumber"
            label="入库数量(kg)"
          ></el-table-column>
          <el-table-column prop="remainNumber" label="剩余数量(kg)">
            <template slot-scope="scope">
              <el-tag type="info" v-if="scope.row.remainNumber > 20">{{
                scope.row.remainNumber
              }}</el-tag>
              <el-tag type="danger" v-else>{{ scope.row.remainNumber }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="inEditDialog(scope.row.id)"
                :disabled="!permissionVisable.traceability_agricultural_update"
              ></el-button>
              <!-- 出库按钮 -->
              <el-tooltip
                effect="dark"
                content="出库"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-upload2"
                  size="mini"
                  @click="deliveryDialog(scope.row.id)"
                  :disabled="
                    !permissionVisable.traceability_agricultural_select
                  "
                ></el-button>
              </el-tooltip>
              <!-- 删除按钮 -->
              <!-- type="danger": 红色警告按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeSuppliesInById(scope.row.id)"
                :disabled="!permissionVisable.traceability_agricultural_delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.pagenum"
          :page-sizes="[4, 6, 8, 10]"
          :page-size="pageInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>

        <!-- 入库图表区 -->
        <el-card style="margin-top: 1rem">
          <div style="display: flex">
            <div ref="inColumnChart" style="width: 50%; height: 376px"></div>
            <div ref="outChart" style="width: 50%; height: 376px"></div>
          </div>
        </el-card>

        <!-- 农资出库的对话框 -->
        <el-dialog
          title="农资出库"
          :visible.sync="deliveryDialogVisible"
          width="23%"
          @close="deliveryDialogClosed"
        >
          <!-- 内容主体区 -->
          <el-form
            :model="deliveryForm"
            :rules="deliveryFormRules"
            ref="deliveryFormRef"
            label-width="100px"
          >
            <!-- ref:引用，指向本身，用于使用自身的方法 -->
            <el-form-item label="农资名称" prop="suppliesName">
              <el-input v-model="deliveryForm.suppliesName" disabled></el-input>
            </el-form-item>
            <el-form-item label="操作人" prop="outOperator">
              <el-select
                v-model="deliveryForm.outOperator"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in personInfoList"
                  :key="item.personName"
                  :label="item.personName"
                  :value="item.personName"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="仓库号" prop="warehouse">
              <el-input v-model="deliveryForm.warehouse" disabled></el-input>
            </el-form-item>
            <el-form-item label="剩余数量kg" prop="remainNumber">
              <el-input v-model="deliveryForm.remainNumber" disabled></el-input>
            </el-form-item>
            <el-form-item label="出库数量kg" prop="outNumber">
              <el-input-number
                v-model="deliveryForm.outNumber"
                controls-position="right"
                :min="0.01"
                :max="deliveryForm.remainNumber"
              ></el-input-number>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="deliveryDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="deliverySupplies"
              >确 定</el-button
            >
          </span>
        </el-dialog>

        <!-- 修改农资入库的对话框 -->
        <el-dialog
          title="修改农资入库"
          :visible.sync="inEditDialogVisible"
          width="23%"
          @close="inEditDialogClosed"
        >
          <!-- 内容主体区 -->
          <el-form
            :model="inEditForm"
            :rules="inEditFormRules"
            ref="inEditFormRef"
            label-width="100px"
          >
            <!-- ref:引用，指向本身，用于使用自身的方法 -->
            <el-form-item label="农资名称" prop="suppliesName">
              <el-input v-model="inEditForm.suppliesName" disabled></el-input>
            </el-form-item>
            <el-form-item label="入库日期">
              <el-date-picker
                v-model="inEditForm.inTime"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="操作人" prop="inOperator">
              <el-select v-model="inEditForm.inOperator" placeholder="请选择">
                <el-option
                  v-for="(item, i) in personInfoList"
                  :key="i"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="仓库号" prop="warehouse">
              <el-input v-model="inEditForm.warehouse"></el-input>
            </el-form-item>
            <el-form-item label="入库数量kg" prop="inNumber">
              <el-input-number
                v-model="inEditForm.inNumber"
                controls-position="right"
                :min="0"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="剩余数量kg" prop="remainNumber">
              <el-input-number
                v-model="inEditForm.remainNumber"
                controls-position="right"
                :min="0"
                :max="inEditForm.inNumber"
              ></el-input-number>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="inEditDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="inEditSuppliesInfo"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </el-tab-pane>

      <!-- 出库记录 -->

      <el-tab-pane label="出库记录">
        <el-col style="width: 100px; float: right; margin-bottom: 10px">
          <el-select v-model="selectType2" @change="typeChange2">
            <el-option
              v-for="item in type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <!-- 列表区域 -->
        <el-table :data="SuppliesOutList" border stripe>
          <!-- :data: 放入数据源 -->
          <!-- border： 加入边框线 -->
          <!-- type="index"： 索引列 -->
          >
          <el-table-column type="index"> </el-table-column>
          <el-table-column
            prop="suppliesName"
            label="农资名称"
          ></el-table-column>
          <el-table-column
            prop="outTime"
            label="出库日期"
            width="180px"
          ></el-table-column>
          <el-table-column prop="outOperator" label="操作员"></el-table-column>
          <el-table-column prop="warehouse" label="仓库号"></el-table-column>
          <el-table-column
            prop="outNumber"
            label="出库数量(kg)"
          ></el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                @click="outEditDialog(scope.row.id)"
                :disabled="!permissionVisable.traceability_agricultural_update"
              ></el-button>
              <!-- 删除按钮 -->
              <!-- type="danger": 红色警告按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="removeSuppliesOutById(scope.row.id)"
                :disabled="!permissionVisable.traceability_agricultural_delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :current-page="pageInfo2.pagenum"
          :page-sizes="[4, 6, 8, 10]"
          :page-size="pageInfo2.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2"
        >
        </el-pagination>

        <!-- 修改农资出库的对话框 -->
        <el-dialog
          title="修改农资出库"
          :visible.sync="outEditDialogVisible"
          width="25%"
          @close="outEditDialogClosed"
        >
          <!-- 内容主体区 -->
          <el-form
            :model="outEditForm"
            :rules="outEditFormRules"
            ref="outEditFormRef"
            label-width="120px"
          >
            <!-- ref:引用，指向本身，用于使用自身的方法 -->
            <el-form-item label="农资名称" prop="suppliesName">
              <el-input v-model="outEditForm.suppliesName" disabled></el-input>
            </el-form-item>
            <el-form-item label="出库日期">
              <el-date-picker
                v-model="outEditForm.outTime"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="操作人" prop="outOperator">
              <el-select v-model="outEditForm.outOperator" placeholder="请选择">
                <el-option
                  v-for="(item, i) in personInfoList"
                  :key="i"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="仓库号" prop="warehouse">
              <el-input v-model="outEditForm.warehouse"></el-input>
            </el-form-item>
            <el-form-item label="出库数量(kg)" prop="outNumber">
              <el-input-number
                v-model="outEditForm.outNumber"
                controls-position="right"
                :min="0"
                :max="constOutNumber + remainNumber"
              ></el-input-number>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="outEditDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="outEditSuppliesInfo"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>

    <!-- 农资入库的对话框 -->
    <el-dialog
      title="农资入库"
      :visible.sync="addDialogVisible"
      width="23%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addeForm"
        :rules="addeFormRules"
        :hide-required-asterisk="true"
        ref="addeFormRef"
        label-width="100px"
      >
        <el-form-item label="投入品类型">
          <el-cascader
            placeholder="请选择投入品类型"
            v-model="valueType"
            :options="categoryOptions"
            @change="handleCategoryChange"
            clearable
            :show-all-levels="false"
          ></el-cascader>
        </el-form-item>
        <!-- ref:引用，指向本身，用于使用自身的方法 -->
        <!-- <el-form-item label="操作类别" prop="type">
          <el-select
            v-model="addeForm.type"
            placeholder="请选择"
            @change="getsuppliesNames"
          >
            <el-option
              v-for="item in options2"
              :key="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="农资名称" prop="suppliesName">
          <el-select v-model="addeForm.suppliesName" placeholder="请选择">
            <el-option
              v-for="item in suppliesNames"
              :key="item.id"
              :label="item.suppliesName"
              :value="item.suppliesName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作人" prop="inOperator">
          <el-select v-model="addeForm.inOperator" placeholder="请选择">
            <el-option
              v-for="(item, i) in personInfoList"
              :key="i"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库号" prop="warehouse">
          <el-input v-model="addeForm.warehouse"></el-input>
        </el-form-item>
        <el-form-item label="入库数量kg" prop="inNumber">
          <el-input-number
            v-model="addeForm.inNumber"
            controls-position="right"
            :min="0.01"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSuppliesIn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      token: window.localStorage.getItem('token'),
      type: [
        {
          value: '全部',
          label: '全部',
        },
      ],
      selectType1: '全部',
      selectType2: '全部',
      record: 0,
      isRed: false,

      // 农资信息
      suppliesNames: [],
      // 入库

      // 保存入库的操作类别选项·
      options2: [
        {
          value: '饲料',
          label: '饲料',
        },
        {
          value: '渔药',
          label: '渔药',
        },
      ],

      // 用于控制分页的当前页码和条数
      pageInfo: {
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 4,
      },

      // 用于农资列表信息
      SuppliesInList: [],

      // 用于存放人员信息
      personInfoList: [],

      // 控制农资入库对话框的显示与隐藏
      addDialogVisible: false,

      // 控制农资出库对话框的显示与隐藏
      deliveryDialogVisible: false,

      // 控制修改农资出库对话框的显示与隐藏
      inEditDialogVisible: false,

      // 入库总条数
      total: 0,

      // 农资入库的表单数据
      addeForm: {
        suppliesName: '',
        inOperator: '',
        warehouse: '',
        inNumber: 0,
        inTime: '',
        baseId: '',
        type: '',
      },

      // 查询到的农资入库的表单数据
      inEditForm: {},

      // 农资出库的表单数据
      deliveryForm: {
        suppliesName: '',
        outTime: '',
        outOperator: '',
        warehouse: '',
        outNumber: '',
        baseId: '',
        suppliesInId: '',
        remainNumber: '',
        type: '',
      },

      // 添加表单的验证规则对象
      addeFormRules: {
        suppliesName: [
          { required: true, message: '请输入农资名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '农资名称的长度在2~10个字符之间',
            trigger: 'blur',
          },
        ],
        inOperator: [
          { required: true, message: '请输入操作人', trigger: 'blur' },
        ],
        type: [{ required: true, message: '请输入操作类别', trigger: 'blur' }],
        warehouse: [
          { required: true, message: '请输入仓库号', trigger: 'blur' },
        ],
        inNumber: [
          { required: true, message: '请输入入库数量', trigger: 'blur' },
        ],
      },

      // 农资出库的验证规则对象
      deliveryFormRules: {
        inOperator: [
          { required: true, message: '请输入操作员', trigger: 'blur' },
        ],
        outNumber: [
          { required: true, message: '请输入出库数量', trigger: 'blur' },
        ],
      },

      // 修改农资入库的验证规则对象
      inEditFormRules: {
        suppliesName: [
          { required: true, message: '请输入农资名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '客户名的长度在2~10个字符之间',
            trigger: 'blur',
          },
        ],
        inOperator: [
          { required: true, message: '请输入操作人', trigger: 'blur' },
        ],
        warehouse: [
          { required: true, message: '请输入仓库号', trigger: 'blur' },
        ],
        inNumber: [
          { required: true, message: '请输入入库数量', trigger: 'blur' },
        ],
        remainNumber: [
          { required: true, message: '请输入剩余数量', trigger: 'blur' },
        ],
      },

      // 出库

      // 用于控制分页的当前页码和条数
      pageInfo2: {
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 4,
      },

      // 出库总条数
      total2: 0,

      // 用于农资列表信息
      SuppliesOutList: [],

      // 通过id获取的出库表单
      outEditForm: {},

      // 控制修改农资出库对话框的显示与隐藏
      outEditDialogVisible: false,

      // 修改农资入库的验证规则对象
      outEditFormRules: {
        suppliesName: [
          { required: true, message: '请输入农资名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '客户名的长度在2~10个字符之间',
            trigger: 'blur',
          },
        ],
        outOperator: [
          { required: true, message: '请输入操作人', trigger: 'blur' },
        ],
        warehouse: [
          { required: true, message: '请输入仓库号', trigger: 'blur' },
        ],
        outNumber: [
          { required: true, message: '请输入出库数量', trigger: 'blur' },
        ],
      },

      // 基地编号
      baseId: this.$store.state.baseId,

      // 由id获取出库数量
      constOutNumber: 0,

      // 获取剩余数量
      remainNumber: 0,

      // 存储入库图表数据
      // 图表横轴，农资
      shrimpType: [],
      // 入库农资剩余量
      inRemainNumber: [],
      // 入库农资消耗量
      inInNumber: [],
      // 存数据数组
      inAll: [],
      outAll: [],
      // 获取全部入库数据
      SuppliesInListAll: [],

      // 出库时间折线图横轴
      outTimeInfo: [],
      // 分类信息
      valueType: [],
      categoryOptions: [],
      // 用于获取农资名称
      suppliesName: [],
    }
  },
  created() {
    this.setNode()
    this.getCategoryOne()
  },
  computed: {
    ...mapState(['permissionVisable']),
    // 入库柱状图数据
    inColumnOption() {
      let that = this
      let option = {
        title: {
          text: '农资目前数量详情',
        },

        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        legend: {
          data: ['剩余量', '消耗量'],
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'category',
            data: this.shrimpType,
          },
        ],
        yAxis: [
          {
            type: 'value',
          },
        ],
        series: [
          {
            name: '剩余量',
            type: 'bar',
            stack: '数量',
            data: this.inRemainNumber,
          },
          {
            name: '消耗量',
            type: 'bar',
            stack: '数量',
            data: this.inInNumber,
          },
        ],
      }

      return option
    },

    // 饼状图数据
    outOption() {
      let that = this
      let option = {
        backgroundColor: '#fff',

        title: {
          text: '农资剩余比例',
          left: 'center',
          top: 20,
          textStyle: {
            color: '#000',
          },
        },

        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)',
        },

        visualMap: {
          show: false,
          min: 80,
          max: 600,
          inRange: {
            colorLightness: [0, 1],
          },
        },
        series: [
          {
            name: '农资',
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            data: this.outAll.sort(function (a, b) {
              return a.value - b.value
            }),
            roseType: 'radius',
            label: {
              color: '#000',
            },
            labelLine: {
              lineStyle: {
                color: '#666',
              },
              smooth: 0.2,
              length: 10,
              length2: 20,
            },
            itemStyle: {
              color: '#c23531',
              shadowBlur: 200,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },

            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx) {
              return Math.random() * 200
            },
          },
        ],
      }
      return option
    },
  },
  methods: {
    // 获取一级分类
    async getCategoryOne() {
      const { data: res } = await this.$http.post('/inputcategory/search', {
        baseId: this.baseId,
      })
      let categorySet = res.data
      categorySet.forEach((item) => {
        let categoryObj = {}
        let children = []
        categoryObj.value = item.typeOne
        categoryObj.label = item.typeOne
        categoryObj.id = item.id
        categoryObj.children = children
        this.categoryOptions.push(categoryObj)
      })
      this.categoryOptions.forEach((item) => {
        this.getCategoryTwo(item)
      })
      console.log(this.categoryOptions)
    },
    // 获取二级分类
    async getCategoryTwo(itemInner) {
      const { data: res } = await this.$http.post(
        '/inputcategoryinter/search',
        {
          firstLevelId: itemInner.id,
        }
      )
      res.data.forEach((item) => {
        let typeTwoObj = {}
        typeTwoObj.value = item.typeTwo
        typeTwoObj.label = item.typeTwo
        this.type.push(typeTwoObj)
        typeTwoObj.id = item.id
        itemInner.children.push(typeTwoObj)
      })
    },
    // 监听分类改变事件
    handleCategoryChange(value) {
      this.addeForm.type = value[value.length - 1]
      this.addeForm.suppliesName = ''
      this.getsuppliesNames()
    },
    // 页面刷新 再次获取baseId
    setNode() {
      if (this.baseId !== '') {
        this.getSuppliesInList()
        this.getSuppliesInListAll().then(() => {
          this.getInColumnData()
          this.getOutData()
        })
        this.getSuppliesOutList()
        this.getPersonInfoList()
      } else {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        setTimeout(() => {
          this.baseId = this.defines.baseId
          this.getSuppliesInList()
          this.getSuppliesInListAll().then(() => {
            this.getInColumnData()
            this.getOutData()
          })
          this.getSuppliesOutList()
          this.getPersonInfoList()
          loading.close()
        }, 1500)
      }
    },
    // 入库分类
    async typeChange1() {
      if (this.selectType1 === '全部') {
        this.getSuppliesInList()
      } else {
        this.pageInfo.pagenum = 1
        this.pageInfo.pagesize = 4
        const { data: res } = await this.$http.post(
          `/suppliesin/search/${this.pageInfo.pagenum}/${this.pageInfo.pagesize}`,
          {
            baseId: this.baseId,
            type: this.selectType1,
          }
        )
        this.SuppliesInList = res.data.rows
        this.total = res.data.total
      }
    },
    // 出库分类
    async typeChange2() {
      if (this.selectType2 === '0') {
        this.getSuppliesOutList()
      } else {
        this.pageInfo2.pagenum = 1
        this.pageInfo2.pagesize = 4
        const { data: res } = await this.$http.post(
          `/suppliesout/search/${this.pageInfo2.pagenum}/${this.pageInfo2.pagesize}`,
          {
            baseId: this.baseId,
            type: this.selectType2,
          }
        )
        this.SuppliesOutList = res.data.rows
        this.total2 = res.data.total
      }
    },

    // 分类获取农资信息
    async getsuppliesNames() {
      const { data: res } = await this.$http.post('/suppliesinfo/search', {
        baseId: this.baseId,
        type: this.addeForm.type,
      })
      if (res.code !== 20000) {
        return this.$message.error('分类获取农资名称失败！！')
      }
      this.suppliesNames = res.data
      console.log(this.suppliesNames)
    },

    // 入库

    // 入库柱状图
    getInColumnData() {
      const chart = this.$refs.inColumnChart
      if (chart) {
        // 初始化目标图表
        const myChart = this.$echarts.init(chart)
        // 显示图表数据
        myChart.setOption(this.inColumnOption)
        // 监听窗口变化调用resize
        window.addEventListener('resize', function () {
          myChart.resize()
        })
      }
      this.$on('hook:destroyed', () => {
        window.removeEventListener('resize', function () {
          myChart.resize()
        })
      })
    },

    // 入库折线图
    getOutData() {
      const chart = this.$refs.outChart
      if (chart) {
        // 初始化目标图表
        const myChart = this.$echarts.init(chart)
        // 显示图表数据
        myChart.setOption(this.outOption)
        // 监听窗口变化调用resize
        window.addEventListener('resize', function () {
          myChart.resize()
        })
      }
      this.$on('hook:destroyed', () => {
        window.removeEventListener('resize', function () {
          myChart.resize()
        })
      })
    },

    // 获取入库记录
    async getSuppliesInList() {
      const { data: res } = await this.$http.post(
        `/suppliesin/search/${this.pageInfo.pagenum}/${this.pageInfo.pagesize}`,
        {
          baseId: this.baseId,
        }
      )
      if (res.code !== 20000) {
        return this.$message.error('获取入库记录失败！！')
      }
      this.SuppliesInList = res.data.rows
      this.total = res.data.total
    },

    // 获取图表数据
    async getSuppliesInListAll() {
      const { data: res } = await this.$http.post('/suppliesin/search', {
        type: '',
        baseId: this.baseId,
      })
      console.log(res)
      this.SuppliesInListAll = res.data
      console.log(this.SuppliesInListAll)
      // 数组中抽取其中虾的名称种类成新数组
      this.SuppliesInListAll.forEach((item) => {
        this.shrimpType.push(item.suppliesName)
      })
      let arr1 = []
      let arr2 = []
      // 数组去重（数组下标判断法：如果当前数组的第 i 项在当前数组中第一次出现的位置不是 i，那么表示第 i 项是重复的，忽略掉
      this.shrimpType = this.shrimpType.filter((val, index, arr) => {
        return arr.indexOf(val) === index
      })
      // 将数组中重复的名称值相加
      this.shrimpType.forEach((item) => {
        // 创建只存三个值的空数组
        let emptyObj = { suppliesName: '', remainNumber: 0, inNumber: 0 }
        let emptyObj1 = { name: '', value: 0 }
        // 分好类型
        emptyObj.suppliesName = item
        emptyObj1.name = item
        arr1.push(emptyObj)
        arr2.push(emptyObj1)
      })
      // 循环相同的key值相加
      this.SuppliesInListAll.forEach((item) => {
        arr1.forEach((item1) => {
          if (item.suppliesName === item1.suppliesName) {
            item1.remainNumber += item.remainNumber
            item1.inNumber += item.inNumber
          }
        })
        arr2.forEach((item2) => {
          if (item.suppliesName === item2.name) {
            item2.value += item.remainNumber
          }
        })
      })
      this.inAll = arr1
      this.outAll = arr2
      // 数组中抽取其中虾的名称种类成新数组
      arr1.forEach((item) => {
        this.inRemainNumber.push(item.remainNumber.toFixed(1))
        this.inInNumber.push((item.inNumber - item.remainNumber).toFixed(1))
      })
      console.log(arr1)
      console.log(arr2)
    },

    // 获取人员信息
    async getPersonInfoList() {
      const { data: res } = await this.$http.get(`${this.$limit}/user/getBaseMember`, {
        headers: {
          Authorization: this.token
        }
      })
      this.personInfoList = res.data
      console.log(this.personInfoList)
    },

    // 监听pagesize(每页显示条数)改变事件
    handleSizeChange(newSize) {
      this.pageInfo.pagesize = newSize
      this.getSuppliesInList()
    },

    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.pageInfo.pagenum = newPage
      this.getSuppliesInList()
    },

    // 监听农资入库对话框的关闭事件,关闭时对表单进行重置
    addDialogClosed() {
      // 表单方法：resetFields：对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.addeFormRef.resetFields()
      this.valueType = []
    },

    // 监听农资出库对话框的关闭事件，关闭时对表单进行重置
    deliveryDialogClosed() {
      this.$refs.deliveryFormRef.resetFields()
    },

    // 监听修改农资出库对话框的关闭事件，关闭时对表单进行重置
    inEditDialogClosed() {
      this.$refs.inEditFormRef.resetFields()
    },

    // 点击按钮，农资入库
    addSuppliesIn() {
      // 先进行表单的预校验
      this.$refs.addeFormRef.validate(async (valid) => {
        // 表单自身方法：validate：进行表单预验证，放回验证结果，用valid接收
        if (!valid) return false
        // 成功后，可以发起添加用户的网络请求
        // 调用添加用户接口
        var date = new Date()
        this.addeForm.inTime = `${date.getFullYear()}-${
          date.getMonth() + 1
        }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
        this.addeForm.baseId = this.baseId
        const { data: res } = await this.$http.post(
          '/suppliesin',
          this.addeForm
        )
        console.log(res)
        if (res.code !== 20000) {
          return this.$message.error('农资入库失败！！')
        }
        this.$message.success('农资入库成功!!')
        // 隐藏添加的对话框
        this.addDialogVisible = false
        this.selectType1 = ''
        // 刷新
        this.getSuppliesInList()
        this.getSuppliesInListAll().then(() => {
          this.getInColumnData()
          this.getOutData()
        })
      })
    },

    // 农资出库的对话框
    async deliveryDialog(id) {
      // 调用根据ID查询农资信息接口
      const { data: res } = await this.$http.get('/suppliesin/' + id)
      if (res.code !== 20000) {
        return this.$message.error('查询农资信息失败！！')
      }
      this.deliveryForm.baseId = res.data.baseId
      this.deliveryForm.type = res.data.type
      this.deliveryForm.warehouse = res.data.warehouse
      this.deliveryForm.suppliesInId = res.data.id
      this.deliveryForm.suppliesName = res.data.suppliesName
      this.deliveryForm.remainNumber = res.data.remainNumber
      this.deliveryDialogVisible = true
    },

    // 提交农资出库信息
    deliverySupplies() {
      // 先进行表单的预验证
      this.$refs.deliveryFormRef.validate(async (valid) => {
        if (!valid) return false
        // 正确，则会发起修改用户信息的请求

        // 添加网络时间
        var date = new Date()
        this.deliveryForm.outTime = `${date.getFullYear()}-${
          date.getMonth() + 1
        }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`

        const { data: res } = await this.$http.post('/suppliesout', {
          suppliesName: this.deliveryForm.suppliesName,
          outTime: this.deliveryForm.outTime,
          outOperator: this.deliveryForm.outOperator,
          warehouse: this.deliveryForm.warehouse,
          outNumber: this.deliveryForm.outNumber,
          baseId: this.deliveryForm.baseId,
          type: this.deliveryForm.type,
          suppliesInId: this.deliveryForm.suppliesInId,
        })
        if (res.code !== 20000) {
          return this.$message.error('农资出库失败！！')
        }
        // 关闭对话框
        this.deliveryDialogVisible = false
        // 刷新农资列表
        this.getSuppliesInList()
        this.getSuppliesInListAll().then(() => {
          this.getInColumnData()
          this.getOutData()
        })

        // 刷新出库记录
        this.getSuppliesOutList()

        // 提示成功
        this.$message.success('农资出库成功！！')
      })
    },

    // 展示入库修改的对话框
    async inEditDialog(id) {
      // 调用根据ID查询用户信息接口
      const { data: res } = await this.$http.get('/suppliesin/' + id)
      if (res.code !== 20000) {
        return this.$message.error('查询农资入库信息失败！！')
      }
      this.inEditForm = res.data
      this.inEditDialogVisible = true
    },

    // 修改入库信息并提交
    inEditSuppliesInfo() {
      // 先进行表单的预验证
      this.$refs.inEditFormRef.validate(async (valid) => {
        if (!valid) return false
        // 正确，则会发起修改用户信息的请求
        var date = new Date(this.inEditForm.inTime)
        this.inEditForm.inTime = `${date.getFullYear()}-${
          date.getMonth() + 1
        }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
        const { data: res } = await this.$http.put(
          '/suppliesin/' + this.inEditForm.id,
          {
            suppliesName: this.inEditForm.suppliesName,
            inTime: this.inEditForm.inTime,
            inOperator: this.inEditForm.inOperator,
            warehouse: this.inEditForm.warehouse,
            inNumber: this.inEditForm.inNumber,
            baseId: this.inEditForm.baseId,
            remainNumber: this.inEditForm.remainNumber,
            type: this.inEditForm.type,
          }
        )
        if (res.code !== 20000) {
          return this.$message.error('更新客户信息失败！！')
        }
        // 关闭对话框
        this.inEditDialogVisible = false
        // 刷新用户列表
        this.getSuppliesInList()
        this.getSuppliesInListAll().then(() => {
          this.getInColumnData()
          this.getOutData()
        })

        // 提示修改成功
        this.$message.success('更新客户信息成功！！')
      })
    },

    // 根据农资id删除对应的入库信息
    async removeSuppliesInById(id) {
      // 弹框询问用户是否删除数据
      // 前提：在elementUI中挂载confirm
      // （提示消息，标题文本，｛确认按钮的文本，取消按钮的文本，提示的类型｝）
      const confirmResult = await this.$confirm(
        '此操作将永久删除该记录, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
        // .catch 用于捕获错误返回给confirmResult
      ).catch((err) => {
        return err
      })
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除， 则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        // this.$message.info: 灰色提示框
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/suppliesin/' + id)
      if (res.code !== 20000) {
        return this.$message.error('删除客户失败')
      }
      this.$message.success('删除客户成功！！')
      this.getSuppliesInList()
      this.getSuppliesInListAll().then(() => {
        this.getInColumnData()
        this.getOutData()
      })
    },

    // 出库

    // 获取出库记录
    async getSuppliesOutList() {
      const { data: res } = await this.$http.post(
        `/suppliesout/search/${this.pageInfo2.pagenum}/${this.pageInfo2.pagesize}`,
        {
          baseId: this.baseId,
        }
      )
      console.log(res)
      if (res.code !== 20000) {
        return this.$message.error('获取入库记录失败！！')
      }
      this.SuppliesOutList = res.data.rows
      this.total2 = res.data.total
    },

    // 监听出库pagesize(每页显示条数)改变事件
    handleSizeChange2(newSize) {
      this.pageInfo2.pagesize = newSize
      this.getSuppliesOutList()
    },

    // 监听出库页码值改变的事件
    handleCurrentChange2(newPage) {
      this.pageInfo2.pagenum = newPage
      this.getSuppliesOutList()
    },

    // 监听修改农资出库对话框的关闭事件，关闭时对表单进行重置
    outEditDialogClosed() {
      this.$refs.outEditFormRef.resetFields()
    },

    // 展示修改的对话框
    async outEditDialog(id) {
      // 调用根据ID查询用户信息接口
      const { data: res } = await this.$http.get('/suppliesout/' + id)
      if (res.code !== 20000) {
        return this.$message.error('查询农资出库信息失败！！')
      }
      this.outEditForm = res.data
      this.constOutNumber = this.outEditForm.outNumber
      this.outEditDialogVisible = true
      const { data: res2 } = await this.$http.get(
        '/suppliesin/' + this.outEditForm.suppliesInId
      )
      if (res2.code !== 20000) {
        return this.$message.error('查询农资剩余数量信息失败！！')
      }
      this.remainNumber = res2.data.remainNumber
    },

    // 修改出库信息并提交
    outEditSuppliesInfo() {
      // 先进行表单的预验证
      this.$refs.outEditFormRef.validate(async (valid) => {
        if (!valid) return false
        // 正确，则会发起修改用户信息的请求
        var date2 = new Date(this.outEditForm.outTime)
        this.outEditForm.outTime = `${date2.getFullYear()}-${
          date2.getMonth() + 1
        }-${date2.getDate()} ${date2.getHours()}:${date2.getMinutes()}:${date2.getSeconds()}`

        console.log(this.outEditForm.outTime)
        const { data: res } = await this.$http.put(
          '/suppliesout/' + this.outEditForm.id,
          {
            suppliesName: this.outEditForm.suppliesName,
            outTime: this.outEditForm.outTime,
            outOperator: this.outEditForm.outOperator,
            warehouse: this.outEditForm.warehouse,
            outNumber: this.outEditForm.outNumber,
            baseId: this.outEditForm.baseId,
            suppliesInId: this.outEditForm.suppliesInId,
            type: this.outEditForm.type,
          }
        )
        if (res.code !== 20000) {
          return this.$message.error('更新出库记录失败！！')
        }
        // 关闭对话框
        this.outEditDialogVisible = false
        // 清空剩余数量数据
        this.remainNumber = 0
        // 刷新用户列表
        this.getSuppliesOutList()
        this.getSuppliesInListAll().then(() => {
          this.getInColumnData()
          this.getOutData()
        })

        // 提示修改成功
        this.$message.success('更新出库记录成功！！')
      })
    },

    // 根据农资id删除对应的出库信息
    async removeSuppliesOutById(id) {
      // 弹框询问是否删除数据
      // 前提：在elementUI中挂载confirm
      // （提示消息，标题文本，｛确认按钮的文本，取消按钮的文本，提示的类型｝）
      const confirmResult = await this.$confirm(
        '此操作将永久删除该记录, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
        // .catch 用于捕获错误返回给confirmResult
      ).catch((err) => {
        return err
      })
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除， 则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        // this.$message.info: 灰色提示框
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/suppliesout/' + id)
      if (res.code !== 20000) {
        return this.$message.error('删除客户失败')
      }
      this.$message.success('删除客户成功！！')
      this.getSuppliesOutList()
      this.getSuppliesInListAll().then(() => {
        this.getInColumnData()
        this.getOutData()
      })
    },
  },
}
</script>

<style lang="less" scoped>
.red {
  color: red;
}
</style>
